<?php

namespace common\service;

use common\model\OriginalPlanNodeModel;

use common\model\TaskModel;
use common\model\TaskWorkOrderModel;
use support\SingletonTrait;

class ReportsService
{
    use SingletonTrait;

    public function __construct() {

    }

    /**
     * 报表-生产日报-原计划交付的节点数据
     * @param int   $projectId
     * @param int   $tenantId
     * @param int $startTime
     * @param int $endTime
     *
     * @return array
     */
    public function getDeliveryPlanNodeTaskIds(int $projectId,int $tenantId,int $startTime, int $endTime , $page)
    {
        //组装条件
        $where =[
            'project_id' => $projectId,
            // 完成时间
            'delivery_time' => ['between', [$startTime, $endTime]],
            //组户id
            'tenant_id' => $tenantId,
            // 节点类型（2=完成节点）
            'node_type' => OriginalPlanNodeModel::NODE_TYPE_DELIVERY
        ];

        $fields = [
            'all_task_ids', // 任务ID集合
            'delivery_task_ids', // 交付任务ID集合
            'deprecated_task_ids', //废除任务ids
            'stage',// stage 所处阶段 1=T1, 2=非T1
            'step_category_id', // 环节ID
            'stage_id', // 阶段ID
            'episode_id' // 剧集id
        ];

        $result= model(OriginalPlanNodeModel::class)
            ->field($fields)
            ->where($where)
            ->page(...$page)
            ->select();


        if(empty($result)){
            return [
                'max_count' => 50,
                'delivery_plan_node' => [],
            ];
        }

        $data = [
            // 最大允许分页数 最大允许分页数
            'max_count' => 50,
            'delivery_plan_node' => $result,
        ];


        return $data;
    }

    /**
     * 报表-已交付的节点数据
     * @param int $projectId
     * @param int $tenantId
     * @param int $startTime
     * @param int $endTime
     * @param array $page
     *
     * @return array
     */
    public function getDeliveredTaskIds(int $projectId,int $tenantId,int $startTime, int $endTime,array $page)
    {
        $where = [
            'project_id' => $projectId,
            'tenant_id' => $tenantId,
            'delivery_time' => ['between', [$startTime, $endTime]],
        ];

        $fields = [
            "id", // 任务id
            "step_category_id", // 环节id
            "step_id", // 工序id
            "step_type", // 任务工序关联类型
            "plan_start_time", // 计划制作开始时间
            "plan_end_time", // 计划制作截至时间
            "overdue_count", // 逾期次数
            "delivery_time", // 交付时间
            "plan_delivery_time" // 原计划交付时间
        ];
        $result = model(TaskModel::class)
            ->field($fields)
            ->where($where)
            ->page(...$page)
            ->select();


        if(empty($result)){
            return [
                'max_count' => 50,
                'delivery_task' => [],
            ];
        }

        $data =  [
            'max_count' => 50,
            'delivery_task' => $result,
        ];

        return $data;
    }

    /**
     * 未处理的工单数量进行计算
     * @param int $projectId
     * @param int $tenantId
     * @param int $startTime
     * @param int $endTime
     *
     * @return array
     */
    public function getUnhandleWorkOrderCount(int $projectId, int $tenantId, int $startTime, int $endTime): array
    {
        if (empty($projectId)) {
            return [
                'number' => 0
            ];
        }
        $projectIds = TaskWorkOrderService::getInstance()->getProjectByBelongProjectId((string)$projectId, $tenantId);
        array_push($projectIds, $projectId);
        $where = [
            'two.status' => ['in', [TaskWorkOrderModel::STATUS_UNTREATED, TaskWorkOrderModel::STATUS_PROGRESS]],
            'two.project_id' => ['IN', $projectIds],
            'two.type' => 'task_making',
            'two.created' => ['between', [$startTime, $endTime]],
//            'two.tenant_id' => $tenantId
        ];
        // 查询数据
        $result = model(TaskWorkOrderModel::class)->alias('two')
            ->field('count(two.id) as number')
            ->where($where)
            ->select();

        if (empty($result)) {
            return [
                'number' => 0
            ];
        }
        return $result;
    }


    /**
     * 报表-处理指定的时间内的未处理的工单数
     * @param array   $param
     * @param int   $projectId
     * @param int   $tenantId
     * @param int   $startTime
     * @param int   $endTime
     * @param array $page
     *
     * @return array
     */
    public function getUnhandleWorkOrderList(array $param,int $projectId, int $tenantId, int $startTime, int $endTime,array $page): array
    {
        //组装查询条件
        $where = [
            'two.status' => ['in', [TaskWorkOrderModel::STATUS_UNTREATED, TaskWorkOrderModel::STATUS_PROGRESS]],
            'two.project_id' => $projectId,
            'two.type' => 'task_making',
            'twopsc.is_confirm' => ['in',['default','no']],
            'two.created' => ['between', [$startTime, $endTime]],
            'two.tenant_id' => $tenantId
        ];

		//构建新查询条件
		$this->buildTaskWorkOrderSerach($param , $where);

		$fields = [
			'two.id',
			'project.name as project_name',
			'two.task_id',
			'two.name',
			'two.type',
			'two.step_id',
			'two.category_id',
			'two.status',
			'two.step_category_id',
			'two.report_type',
			'two.report_content',
			'two.created',
			'two.deadline_time',
			'sc.name step_category_name',
			'sc.code step_category_code',
			'step.name as step_name',
			'step.code as step_code',
			'task.name as task_name',
			'task.code as task_code'
		];
        $result = model(TaskWorkOrderModel::class)->alias('two')
            ->join('task_work_order_problem_step_category twopsc on twopsc.task_work_order_id = two.id','left')
			->join('step on step.id = two.step_id','left')
			->join('step_category sc on sc.id = two.step_category_id','left')
			->join('task on task.id = two.task_id' ,'left')
			->join('project on project.id = two.project_id','left')
            ->field($fields)
            ->where($where)
            ->page(...$page)
            ->select();

        if(empty($result)){
            return [];
        }

        return $result;
    }

	/**
	 * 构建自定义查询的条件
	 * @param $buildSearch
	 * @param $where
	 * @return void
	 */
	private function buildTaskWorkOrderSerach(array $buildSearch , &$where)
	{
		//拼装$buildSerach不同条件参数
		if(!empty($buildSearch['step_category_id'])){
			$where['two.step_category_id'] = $buildSearch['step_category_id'];
		}
		if(!empty($buildSearch['step_id'])){
			$where['two.step_id'] = $buildSearch['step_id'];
		}
		if(!empty($buildSearch['task_id'])){
			$where['two.task_id'] = $buildSearch['task_id'];
		}
		if(!empty($buildSearch['status'])){
			$where['two.status'] = $buildSearch['status'];
		}
		if(!empty($buildSearch['report_type'])){
			$where['two.report_type'] = $buildSearch['report_type'];
		}
		if(!empty($buildSearch['report_content'])){
			$where['two.report_content'] = ['like',"%{$buildSearch['report_content']}%"];
		}
	}

}
